<template>
  <div class="goods_sku">
    <el-form class="Mssg_form">
      <el-form-item label-width="0px" class="label-title" style="padding-bottom: 5px">
        <span class="label-index" style="background: #005aa0; color: white">5</span>
        <span style="color: black">SKU</span>
        <span class="label-tail"></span>
      </el-form-item>
      <el-button type="default" size="small" icon="el-icon-plus" @click="addSku">新增sku</el-button>
      <e-table
        :table-head-config="tableHeadConfig"
        :table-load-data="tableLoadData"
        :obj-deploy="objDeploy"
        style="margin-top: 20px; height: auto; overflow-y: scroll"
        @selectLine="handleSelectionChange"
      >
        <template v-slot:status="slotData">
          <el-switch
            v-model="slotData.data.row.isShelves"
            :active-value="1"
            :inactive-value="0"
            active-color="#67C23A"
            inactive-color="#909399"
            @change="handleStatusChange(slotData.data.row.isShelves, slotData.data.row)"
          ></el-switch>
        </template>
        <template v-slot:sex="slotData">
          <span
            v-for="item in slotData.data.row.attrList"
            :key="item.id"
            type="success"
            style="margin-right: 2px"
          >{{ item.name + ' , ' }}</span>
        </template>
        <template v-slot:operation="slotData">
          <el-button type="text" size="mini" @click="handleEdit(slotData.data.row)">编辑</el-button>
          <el-button type="text" size="mini" @click="handleCope(slotData.data.row)">复制</el-button>
          <el-button
            type="text"
            size="mini"
            @click="deletSku(slotData.data.row.id, slotData.data.$index)"
          >删除</el-button>
        </template>
      </e-table>
      <div style="margin-top: 15px">
        <el-button type="default" size="small" @click="batchStoreOption(1)">批量上架</el-button>
        <el-button type="default" size="small" @click="batchStoreOption(0)">批量下架</el-button>
        <el-button type="default" size="small" @click="BatchDelteGoodsSku">批量删除</el-button>
      </div>
      <!-- 新增sku弹窗 -->
      <el-dialog
        v-if="false"
        title="新增sku"
        :visible.sync="skuDialogState"
        width="1000px"
        :close-on-click-modal="false"
        @close="cancelSkuDialog"
      >
        <el-form ref="formRef" :model="form" label-width="85px" size="small">
          <el-form-item label-width="0px" class="label-title">
            <span class="label-index">1</span>
            <span>基本信息</span>
            <span class="label-tail"></span>
          </el-form-item>
          <el-row>
            <el-col :span="8">
              <el-form-item label="规格名称:" :required="true">
                <el-input v-model.trim="myForm.name" maxlength="15" placeholder="规格名称" style="width: 100%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="供应商商品编码:" label-width="120px">
                <el-input
                  v-model.trim="myForm.supplierCode"
                  style="width: 100%"
                  placeholder="sku编码"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="69码:">
                <el-input v-model="myForm.barCode" placeholder="69码" style="width: 100%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label-width="0px" class="label-title">
            <span class="label-index">2</span>
            <span>属性设置</span>
            <span class="label-tail"></span>
          </el-form-item>
          <el-row>
            <el-col :span="8">
              <el-form-item label-width="0px" class="label-title">
                <span class="label-index">3</span>
                <span>价格设置</span>
                <span class="label-tail"></span>
              </el-form-item>
              <el-form-item label="批发价:" :required="true">
                <el-input
                  v-model="myForm.tradePrice"
                  placeholder="请输入"
                  :maxlength="18"
                  @input="inputControl(myForm, 'tradePrice', 2)"
                ><i slot="suffix" class="el-input__text">元</i></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="0px" class="label-title">
                <span class="label-index">4</span>
                <span>SKU图片</span>
                <span class="label-tail"></span>
              </el-form-item>
              <el-form-item label-width="120px" label="SKU图片上传" :required="true">
                <el-upload
                  :action="uploadUrl"
                  :data="{ useDay: 1, path: 'upload/portals/marchant' }"
                  list-type="picture-card"
                  :on-preview="licensePreview"
                  :on-success="storeImgSuccessOption"
                  :file-list="fileList"
                  :limit="1"
                  :on-remove="RemoveblicenseImg"
                >
                  <span>上传图片</span>
                </el-upload>
                <el-dialog :visible.sync="skuDialog">
                  <img width="100%" :src="skuImageUrl" alt="" />
                </el-dialog>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="0px" class="label-title">
                <span class="label-index">5</span>
                <span>上架设置</span>
                <span class="label-tail"></span>
              </el-form-item>
              <el-form-item label="是否上架">
                <el-switch
                  v-model="isShelvesStatus"
                  @change="isShelvesStatus ? (myForm.isShelves = 1) : (myForm.isShelves = 0)"
                ></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelSkuDialog">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </div>
      </el-dialog>
    </el-form>
    <public-dialog
      :title="title"
      :visible="visible"
      :custom-class="'sku-view'"
      @handle-cancel="handleCancel"
      @after-close="afterClosed"
    >
      <el-form ref="formRef" :model="myForm" label-width="85px" size="small">
        <el-form-item label-width="0px" class="label-title">
          <span class="label-index">1</span>
          <span>基本信息</span>
          <span class="label-tail"></span>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="季度" :required="true" label-width="55px">
              <el-select v-model="myForm.quarter" placeholder="请选择">
                <el-option label="1" :value="1"></el-option>
                <el-option label="2" :value="2"></el-option>
                <el-option label="3" :value="3"></el-option>
                <el-option label="4" :value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="供应商编码" label-width="95px">
              <el-input
                v-model.trim="myForm.supplierCode"
                style="width: 100%"
                placeholder="sku编码"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="69码" label-width="55px">
              <el-input v-model.trim="myForm.barCode" placeholder="69码" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label-width="0px" class="label-title">
          <span class="label-index">2</span>
          <span>属性设置</span>
          <span class="label-tail"></span>
        </el-form-item>
        <el-row :gutter="10">
          <el-col v-for="item in options" :key="item.value" :span="6">
            <el-form-item :label="item.label" :required="true" label-width="55px">
              <el-select v-model="item.attributeId" style="width: 100%;" filterable placeholder="请选择颜色" clearable>
                <el-option v-for="n in item.children" :key="n.value" :label="n.label" :value="n.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label-width="0px" class="label-title">
              <span class="label-index">3</span>
              <span>价格设置</span>
              <span class="label-tail"></span>
            </el-form-item>
            <el-form-item label="进货价" :required="true">
              <el-input
                v-model="myForm.tradePrice"
                placeholder="请输入"
                :maxlength="18"
                style="width: 100px;"
                @input="calculationPrice(myForm, 'tradePrice')"
              ><i slot="suffix" class="el-input__text">元</i></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="0px" class="label-title">
              <span class="label-index">4</span>
              <span>SKU图片</span>
              <span class="label-tail"></span>
            </el-form-item>
            <el-form-item label-width="120px" label="SKU图片上传" :required="true">
              <SingleUpload :image-url="myForm.fullImgUrl" @on-upload="handleUploader" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="0px" class="label-title">
              <span class="label-index">5</span>
              <span>上架设置</span>
              <span class="label-tail"></span>
            </el-form-item>
            <el-form-item label="是否上架">
              <el-switch
                v-model="myForm.isShelves"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <el-button size="small" @click="handleCancel">取 消</el-button>
        <el-button type="primary" size="small" @click="handleConfirm">确 定</el-button>
      </template>
    </public-dialog>
  </div>
</template>

<script>
import { Basic } from '@/api/base'
import BigNumber from 'bignumber.js'
import eTable from '@/components/table/PublicTable'
import PublicDialog from '@/components/Dialog/PublicDialog'
import SingleUpload from '@/components/SingleUpload'
import {
  deletGoodsSku,
  addGoodsSku,
  updataBatch,
  BatchGoodsSku
} from '@/api/goods'
import { AttributeByAttrId } from '@/api/goodsAttribute'
export default {
  components: {
    eTable,
    PublicDialog,
    SingleUpload
  },
  props: {
    goodsId: {
      type: String,
      default: ''
    },
    supplierId: {
      type: String,
      default: ''
    },
    cateCode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      countStatus: false, // 阶梯价格是否有值的状态
      setGoodsSkus: false,
      priceItem: {
        goodsNum: null,
        disCount: null,
        disPrice: null,
        tradePrice: null,
        creatorId: 1
      },
      skuEncoding: null, // v-model绑定sku编码
      twoAttr: [], // 回显的二级属性数据
      multipleSelection: [], // 全选数据
      redactStatus: false, // 编辑状态
      goodsSkuForm: {}, // 当前sku
      storeId: null, // 暂存商品id
      skuDialogState: false, // sku弹窗状态
      objDeploy: {
        selection: true, // 多选状态
        index: true, // 序号
        pageSize: 10,
        pageNum: 1,
        pagecount: 0
      },
      // 表格标题
      tableHeadConfig: [
        { label: '规格名称', field: 'name' },
        { label: 'sku编码', field: 'skuCode' },
        { label: '属性组', field: 'attrList', columnType: 'slot', slotName: 'sex' },
        { label: '上架状态', field: 'isShelves', columnType: 'slot', slotName: 'status' },
        { label: '操作', columnType: 'slot', slotName: 'operation', width: 260 }
      ],
      tableLoadData: [], // sku列表数据
      skuDialog: false, // sku图弹窗
      skuImageUrl: null, // sku图弹窗地址
      uploadUrl: `${process.env.VUE_APP_FILE_URL}/cloudApi/datacenter/file/uploadFile`, // 图片地址
      imgBaseUrl: process.env.VUE_APP_FILE_URL_OBS, // obs图片地址
      attrData: [],
      fileList: [],
      goodsSkuItem: {},
      arrList: [],
      isShelvesStatus: true, // v-model绑定是否上架
      styleForm: null, // v-model绑定风格
      colourForm: null, // v-model绑定颜色
      sezeForm: [], // v-model绑定尺码
      styledData: [], // 风格数据
      colourData: [], // 颜色数据
      sizeData: [], // 尺码数据
      myForm: {
        id: '',
        goodsId: this.goodsId, // 商品id
        // name: '', // 规格名称
        quarter: '',
        supplierCode: '', // 供应商商品编码
        supplierId: this.supplierId, // 供应商ID
        barCode: '', // 69码
        secondCateId: this.cateCode, // 类别编码
        colorCode: '', // 颜色编码
        sizeCode: '', // 尺码编码
        attrIds: '', // 属性集合
        tradePrice: 0, // 进货价
        imgUrl: '', // 图片地址
        fullImgUrl: '',
        isShelves: 1 // 是否上架
      },
      storeBannerImgList: [], // 图片数组
      ladderList: [
        {
          goodsNum: '',
          disCount: '',
          disPrice: '',
          tradePrice: '',
          creatorId: 1
        }
      ], // 阶梯价
      checked: false,
      num: 10,
      form: {},
      styleList: {},
      title: '',
      visible: false,
      options: []
    }
  },
  mounted() {
    const vm = this
    vm.getSkuList()
  },
  methods: {
    // 获取sku列表
    getSkuList() {
      const vm = this
      const goodsId = vm.goodsId
      Basic.normal('GoodsSku/selectByGoodsId', { goodsId }).then(res => {
        const { data = [] } = res
        vm.tableLoadData = data
      })
      // getGoodsSku({ goodsId }).then(res => {
      //   const { data = [] } = res
      //   vm.tableLoadData = data
      // })
    },
    // 新增sku的弹窗开关
    addSku() {
      const vm = this
      vm.visible = true
      vm.title = '新增SKU'
      vm.queryAttrData()
    },
    // 获取属性树
    queryAttrData() {
      const vm = this
      // 获取属性树
      if (vm.options.length) {
        return false
      }
      Basic.general('GoodsAttribute/selectListPage').then(res => {
        const { data } = res
        const { records = [] } = data
        vm.options = vm.initTree(records)
      })
    },
    initTree(data) {
      const vm = this
      const arr = JSON.parse(JSON.stringify(data))
      const list = []
      arr.forEach(t => {
        const item = {
          label: t.name,
          value: t.id,
          type: parseInt(t.type),
          attributeId: ''
        }
        if (t.code) {
          item.code = t.code
        }
        if (t.list.length) {
          item.children = vm.initTree(t.list)
        }
        list.push(item)
      })
      return list
    },
    // 编辑SKU
    handleEdit(row) {
      const vm = this
      vm.visible = true
      if (vm.options.length) {
        vm.initSku(row)
        return false
      }
      Basic.general('GoodsAttribute/selectListPage').then(res => {
        const { data } = res
        const { records = [] } = data
        vm.options = vm.initTree(records)
      }).then(() => {
        vm.initSku(row)
      })
    },
    // 复制
    handleCope(row) {
      const vm = this
      vm.visible = true
      const data = JSON.parse(JSON.stringify(row))
      data.id = ''
      if (vm.options.length) {
        vm.initSku(data)
        return false
      }
      Basic.general('GoodsAttribute/selectListPage').then(res => {
        const { data } = res
        const { records = [] } = data
        vm.options = vm.initTree(records)
      }).then(() => {
        vm.initSku(data)
      })
    },
    initSku(row) {
      const vm = this
      const data = JSON.parse(JSON.stringify(row))
      console.log('data:', data)
      vm.myForm.id = data.id
      // vm.myForm.name = data.name || ''
      vm.myForm.quarter = data.quarter || ''
      vm.myForm.supplierCode = data.supplierCode || ''
      vm.myForm.barCode = data.barCode || ''
      vm.myForm.tradePrice = data.tradePrice || 0
      vm.myForm.imgUrl = data.imgUrl || ''
      if (data.imgUrl) {
        vm.myForm.fullImgUrl = vm.imgBaseUrl + '/' + data.imgUrl
      }
      // 属性list
      const { attrList = [] } = data
      attrList.forEach(t => {
        vm.options.forEach(j => {
          if (j.type === parseInt(t.type)) {
            j.attributeId = t.id
          }
        })
      })
    },
    // 上传图片
    handleUploader(val) {
      const vm = this
      const formData = new FormData()
      formData.append('file', val.file)
      formData.append('path', 'img_file')
      const url = '/cloudApi/datacenter/file/uploadFile'
      Basic.upLoad(url, formData).then(res => {
        const { data } = res
        const { ip, fileUrl } = data
        vm.myForm.imgUrl = fileUrl
        vm.myForm.fullImgUrl = ip + '/' + fileUrl
      })
    },
    handleCancel() {
      this.visible = false
    },
    afterClosed() {
      const vm = this
      vm.myForm.id = ''
      // vm.myForm.name = ''
      vm.myForm.quarter = ''
      vm.myForm.supplierCode = ''
      vm.myForm.barCode = ''
      vm.myForm.colorCode = ''
      vm.myForm.sizeCode = ''
      vm.myForm.attrIds = ''
      vm.myForm.imgUrl = ''
      vm.myForm.fullImgUrl = ''
      vm.myForm.isShelves = 1
      vm.options.forEach(t => {
        t.attributeId = ''
      })
    },
    handleConfirm() {
      const vm = this
      const params = JSON.parse(JSON.stringify(vm.myForm))
      params.attrIds = vm.options.map(t => t.attributeId).join(',')
      vm.options.forEach(t => {
        if (t.type === 1) {
          // 尺码
          const size = t.children.filter(j => j.value === t.attributeId)
          params.sizeCode = size.length ? size[0].code : ''
        }
        if (t.type === 3) {
          // 颜色
          const color = t.children.filter(j => j.value === t.attributeId)
          params.colorCode = color.length ? color[0].code : ''
        }
      })
      for (let i = 0, len = vm.options.length; i < len; i++) {
        const item = vm.options[i]
        if (!item.attributeId) {
          vm.$message.error(`请选择SKU${item.label}`)
          return false
        }
      }
      // 数据验证
      // if (!params.name) {
      //   vm.$message.error('请输入规格名称')
      //   return false
      // }
      if (!params.quarter) {
        vm.$message.error('请选择季度')
        return false
      }
      if (!params.sizeCode) {
        vm.$message.error('请选择SKU尺码')
        return false
      }
      if (!params.colorCode) {
        vm.$message.error('请选择SKU颜色')
        return false
      }
      if (!params.tradePrice) {
        vm.$message.error('请输入进货价')
        return false
      }
      if (!params.imgUrl) {
        vm.$message.error('请上传SKU图片')
        return false
      }
      vm.save(params)
    },
    save(data) {
      const vm = this
      const params = JSON.parse(JSON.stringify(data))
      Basic.normal('GoodsSku/save', params).then(res => {
        vm.$message({
          message: '保存成功！',
          type: 'success'
        })
        vm.visible = false
        vm.getSkuList()
      })
    },
    // 删除
    // 批量上下架
    async batchStoreOption(num) {
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.$message.warning({ message: '请选择需要' + (num === 1 ? '上' : '下') + '架的商品SKU!' })
        return
      }
      const res = await updataBatch({
        id: this.multipleSelection.map(item => item.id).join(','),
        isShelves: num
      })
      if (res.code === 200) {
        this.$message.success({ message: (num === 1 ? '上架' : '下架') + '成功!' })
        this.multipleSelection = []
        this.getSkuList()
      }
    },
    // 价格设置计算
    calculationPrice(obj, key) {
      const vm = this
      if (key === 'maturityPremia') {
        vm.inputControl(obj, key, 0)
      } else {
        vm.inputControl(obj, key, 2)
      }
      const A = vm.myForm.supplyPrice || 0
      const B = vm.myForm.maturityPremia || 0
      switch (key) {
        case 'supplyPrice':
          if (B) {
            const C = BigNumber(A).multipliedBy(B).dividedBy(100).plus(A).toFixed(2)
            vm.myForm.tradePrice = C
          } else {
            vm.myForm.tradePrice = 0
          }
          break
        case 'maturityPremia':
          if (B) {
            const C = BigNumber(A).multipliedBy(B).dividedBy(100).plus(A).toFixed(2)
            vm.myForm.tradePrice = C
          } else {
            vm.myForm.tradePrice = 0
          }
          break
        case 'tradePrice':
          break
      }
      // 批发价 = 拿货价 + (拿货价 * 溢价比例)
    },
    // sku编码change事件
    skuCodeChange(val) {
      this.skuEncoding = val // sku编码正则匹配的结果赋值
    },
    // 溢价率减减
    subtract(num) {
      this.myForm.maturityPremia--
      if (this.myForm.maturityPremia < 0 || this.myForm.maturityPremia === 0) {
        this.myForm.maturityPremia = 0
      }
    },
    // 阶梯价减减
    ladderPrice(val) {
      val.disCount--
      if (val.disCount < 0 || val.disCount === 0) {
        val.disCount = 0
      }
    },
    // 阶梯价加加
    addLadderPrice(val) {
      val.disCount++
    },
    // 阶梯价格折后率
    disPriceChenge(item) {
      // 折扣率 = 折扣批发价 / 原批发价
      item.disCount = Number(item.disPrice) / Number(item.tradePrice)
      item.disCount = Number(item.disCount.toFixed(2))
      item.disCount = new BigNumber(item.disCount)
      item.disCount = item.disCount.multipliedBy(100)
      this.countStatus = true
      // item.disCount = item.disCount * 100
    },
    // 批发价change事件
    tradePriceChange(val) {
      const { supplyPrice, tradePrice } = this.myForm
      // Number(maturityPremia)
      // 平台批发商品的价格= 拿货价+（溢价比例*拿货价）
      this.myForm.maturityPremia = (Number(tradePrice) - Number(supplyPrice)) / Number(supplyPrice)
      this.myForm.maturityPremia = this.myForm.maturityPremia.toFixed(2)
      this.myForm.maturityPremia = new BigNumber(this.myForm.maturityPremia)
      this.myForm.maturityPremia = this.myForm.maturityPremia.multipliedBy(100)
    },
    // 验证
    validForm() {
      if (!this.myForm.name) {
        this.$message.warning('请输入sku名称!')
        return false
      }
      if (!this.myForm.skuCode) {
        this.$message.warning('请输入sku编码!')
        return false
      }
      if (!this.myForm.supplyPrice) {
        this.$message.warning('请输入拿货价!')
        return false
      }
      if (!this.myForm.tradePrice) {
        this.$message.warning('请输入批发价!')
        return false
      }
      if (!this.myForm.imgUrl) {
        this.$message.warning('请上传图片!')
        return false
      }
      return true
    },
    // 上下架
    async handleStatusChange(val, item) {
      console.log(val)
      const res = await addGoodsSku({ id: item.id, isShelves: val })
      if (res.code === 200) {
        this.$message({ message: (val ? '上架' : '下架') + '成功!', type: 'success' })
      } else {
        this.$message({ message: (val ? '上架' : '下架') + '失败!', type: 'error' })
      }
    },
    // 编辑
    setGoodsSku(item) {
      this.goodsSkuForm = item
      this.skuDialogState = true
      this.redactStatus = true
      this.setGoodsSkus = true
      this.copyGoodsSku()
    },
    // 回显数据
    copyGoodsSku() {
      if (this.goodsSkuForm) {
        // getSkuDetails({id:this.goodsSkuForm.id}).then(res =>{
        //   console.log("sku详情数据",res.data)
        // })
        const {
          name,
          skuCode,
          barCode,
          supplyPrice,
          maturityPremia,
          tradePrice,
          marketPrice,
          isShelves,
          imgUrl,
          attrList,
          priceList
        } = this.goodsSkuForm
        this.myForm.name = name // sku名字
        // this.skuEncoding = skuCode
        this.myForm.skuCode = skuCode // sku编码
        this.myForm.barCode = barCode // 69码
        this.myForm.supplyPrice = supplyPrice // 拿货价
        this.myForm.maturityPremia = maturityPremia // 平台溢价
        this.myForm.tradePrice = tradePrice // 批发价
        this.myForm.marketPrice = marketPrice // 市场价
        this.ladderList = []
        this.ladderList = priceList
        this.myForm.isShelves = isShelves // 是否上架
        isShelves === 1 ? (this.isShelvesStatus = true) : (this.isShelvesStatus = false)
        this.myForm.imgUrl = imgUrl // 图片
        if (!imgUrl) {
          this.fileList = []
        } else {
          this.fileList.push({ url: `${this.imgBaseUrl}/${imgUrl}` }) // 图片回显
        }
        this.twoAttr = attrList
        this.secondLevelProperty(this.attrData) // 回显属性组
      }
    },
    // 复制
    copyClick(val) {
      this.goodsSkuForm = val
      this.skuDialogState = true
      this.redactStatus = true
      this.copyGoodsSku()
      // this.myForm.relationList = []
    },
    // 删除
    deletSku(id, index) {
      this.$confirm('此操作将永久删除该商品SKU, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        deletGoodsSku({ id: id }).then(res => {
          if (res.code === 200) {
            this.tableLoadData.splice(index, 1)
            this.$message({ message: '删除商品SKU成功', type: 'success' })
            this.getSkuList()
          }
        })
      })
    },
    // 新增sku
    async confirm() {
      if (!this.validForm()) return
      // this.myForm.skuCode = this.skuEncoding// sku赋值

      if (this.countStatus) {
        this.myForm.priceList = this.ladderList
      }
      // 有id是编辑
      if (this.goodsSkuForm.id && this.redactStatus && this.setGoodsSkus) {
        this.myForm.id = this.goodsSkuForm.id
        this.addSkuSet('编辑')
      } else {
        this.addSkuSet('新增')
      }
    },
    async addSkuSet(title) {
      if (this.goodsSkuForm) {
        const list = JSON.parse(JSON.stringify(this.arrList))
        list.forEach(t => {
          delete t.id
          delete t.list
          delete t.name
          delete t.value
        })
        const attr = list.map(t => Object.values(t))
        const attrList = attr.join(',').split(',')
        this.myForm.attrIds = attr.join(',')
        this.myForm.relationList = attrList.map(item => ({ attributeId: item }))
      }
      const res = await addGoodsSku(this.myForm)
      if (res.code === 200) {
        this.$message({ message: `${title}成功`, type: 'success' })
        this.getSkuList()
        this.cancelSkuDialog()
        this.myForm.id = null
        this.ladderList = []
        this.myForm.relationList = []
        this.countStatus = false
        this.setGoodsSkus = false
        this.checked = false
        this.redactStatus = false
      }
    },
    // 获取商品分类获取属性
    async secondLevelProperty(item) {
      const vm = this
      item.forEach(async(t, n) => {
        const { id, name } = t
        const key = `attr${n}`
        const item = {}
        item.name = name
        item.value = key
        item[key] = ''
        item.id = id
        const { data } = await AttributeByAttrId({ parentId: id })
        item.list = data.records || []
        vm.arrList.push(item)
        if (this.goodsSkuForm && this.redactStatus) {
          this.twoAttr.forEach(i => {
            data.records.forEach(j => {
              if (i.id === j.id) {
                item[key] = i.id
              }
            })
          })
        }
        console.log('属性组：', vm.arrList)
      })
    },
    // 属性组change事件
    sezeChange(val) {
      // this.myForm.relationList = []
      console.log('sku属性组数据', val)
      const obj = { attributeId: val }
      this.myForm.relationList.push(obj)
    },
    // 图片上传成功的回调
    storeImgSuccessOption(val) {
      if (val.code === 200) {
        this.myForm.imgUrl = val.data.fileUrl
        this.$message({ message: '上传成功', type: 'success' })
      }
    },
    // 查看sku图片
    licensePreview(file) {
      this.skuImageUrl = file.url
      this.skuDialog = true
    },
    // sku照删除
    RemoveblicenseImg(file, fileList) {
      this.myForm.imgUrl = null
    },
    // 取消sku的弹窗开关-- 重置数据
    cancelSkuDialog() {
      // location.reload()//刷新页面
      this.checked = false
      this.skuDialogState = false
      this.$refs.formRef.resetFields()
      this.myForm.imgUrl = null
      this.skuEncoding = null
      this.ladderList = []
      this.arrList = []
      this.fileList = []
      this.myForm.relationList = []
    },
    // 新增阶梯价
    addPriceList() {
      if (!this.ladderList) {
        this.ladderList = []
      }
      const item = JSON.parse(JSON.stringify(this.priceItem))
      this.ladderList.push(item)
    },
    // 删除阶梯价
    skuPrices(index) {
      this.ladderList.splice(index, 1)
    },
    // 阶梯价格多选框
    checkChange(val) {
      console.log(val)
    },
    // 表格全选
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(val)
    },
    // 批量删除
    BatchDelteGoodsSku() {
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.$message.warning({ message: '请选择需要删除的商品SKU!' })
        return
      }
      this.$confirm('此操作将永久删除选中的商品SKU, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        BatchGoodsSku({ id: this.multipleSelection.map(item => item.id).join(',') }).then(res => {
          if (res.code === 200) {
            this.multipleSelection = []
            this.getSkuList()
            this.$message.success({ message: '删除成功!' })
          }
        })
      })
    }
  }
}
</script>
<style lang='scss' scoped>
.goods_sku /deep/ .sku-view {
  width: 985px;
}
.el-input__text {
  font-style: normal;
  color: #666;
}
.goods_sku {
  padding: 20px;
}
.Mssg_form {
  margin-left: 28px;
}

.btnPrices {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.label-title {
  margin: 10px 0 20px;
  span {
    float: left;
  }
  /deep/ .el-form-item__content {
    // font-weight: bold;
    color: #005aa0;
    font-size: 15px;
    line-height: 24px;
  }
  .label-index {
    width: 24px;
    height: 24px;
    line-height: 22px;
    text-align: center;
    border: 1px solid #005aa0;
    border-radius: 24px;
    margin-right: 8px;
    font-weight: normal;
  }
  .label-tail {
    width: 160px;
    height: 12px;
    margin-left: 8px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.15);
  }
}
.sku-premia /deep/ .el-input--suffix .el-input__inner {
  padding: 0px !important;
}
</style>
